/*
 * @Author: pmy
 * @Date: 2021-07-15 10:56:51
 * @LastEditTime: 2023-10-12 10:56:05
 * @LastEditors: tzq
 * @Description: 用于与数据库的接口交互
 * @FilePath: \bdcar-net\src\services\backServices.js
 */
import axios from 'axios'
import Router from '../router/index'
import Store from '../store/index'
import { Notification } from 'element-ui';

export const service = axios.create({
    // service中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: GlobalSetting.IotConfig.RestAPIService,
    // 超时
    timeout: 2000000
})

/**
 * by pmy
 * 请求拦截，除了登录方法都发送一下cookie判断 登录状态
 * @return
 */
service.interceptors.request.use((config) => {
    if (config.url.indexOf(GlobalSetting.IotConfig.LoginService) === -1) {
        const token = localStorage.getItem('token')
        if (token) {
            config.headers.Authorization = 'Bearer ' + token
        }
    }
    return config
})

/**
 * 响应拦截
 */
service.interceptors.response.use(
    function (config) {
        // 如果你想在获取到数据之后做些事情 
        if (config.data.code == 400) {
            Notification({
                type: "error",
                duration: 2000,
                title: '失败',
                message: config.data.msg || '接口调用失败',
                position: "bottom-right"
            })
        } else if (config.data.code == 401) {
            Router.push({
                path: "/"
            });
        }
        return config;
    },
    function (error) {
        if (error.response.status == 401) {
            Router.push({
                path: "/"
            });
        } else {
            Notification({
                type: "error",
                duration: 2000,
                title: '失败',
                message: error.response.statusText ?? "调用失败",
                position: "bottom-right"
            })
        }
        return Promise.reject(error);
    }
);

/**
 * by pmy
 * 系统登录，获取数据访问权限
 * @export
 * @param {*} userName
 * @param {*} passWord
 * @return
 */
export function Login(username, password) {
    return new Promise(function (resolve, reject) {
        console.log("进入backServices/Login")
        console.log(username+"/"+password)
        let data = new FormData();
        data.append("username", username)
        data.append("password", password)
        console.log("1")
        service({
            url: GlobalSetting.IotConfig.LoginService,
            method: 'post',
            data: data
        }).then(res => {
            console.log("2")
            if (res.data.code == 200) {
                localStorage.setItem('token', res.data.data.access_token);
                Store.dispatch("updateCurrentUser", res.data.data);
                resolve(true);
            }
        }).catch((e) => {
            // debugger
            console.error("捕捉的错误:", e)
            reject(false)
            console.log("3 catch了 ")
        })
    })
}

/**
 * by pmy
 * 系统退出服务
 * @export
 * @return
 */
export function Logout() {
    return new Promise(function (resolve, reject) {
        let url = GlobalSetting.IotConfig.RestAPIService + GlobalSetting.IotConfig.Logout;
        service({
            url: url,
            method: 'get',
        }).then(res => {
            if (res.data.code == 200) {
                localStorage.setItem('token', null);
                resolve(true)
            } else {
                console.log('退出失败')
                resolve(false)
            }
        })
    }).catch((err) => {
        reject(err)
    })
};

/**
 * by pmy
 * 获取用户信息
 * @export
 * @return
 */
export function getUserInfor() {
    return service({
        url: "loginByToken",
        method: 'post',
    })
};


